package cn.kgc.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

/**
 * @author: mosin
 * @version: v1.0  2023/1/7
 * shiro 的认证流程
 */
public class TestAuthentication {

    public static void main(String[] args) {
        // 创建安全管理器
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        // 创建域对象  类似数据源
        IniRealm iniRealm = new IniRealm("classpath:user.ini");
        //设置安全管理器的域对象
        defaultSecurityManager.setRealm(iniRealm);
        // 给安全管理工具类 设置安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        // 认证主体  Subject
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("tom", "1234");

        try {
            subject.login(usernamePasswordToken);
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户身份错误");
        }
    }
}
